package com.google.code.opengw.server.deployment;

import java.io.File;
import java.util.List;

import com.google.code.opengw.server.Server;
import com.google.code.opengw.server.domain.Domain;
import com.google.code.opengw.server.support.FileUtils;

public class DeploymentManager implements Runnable {

	private long timeInterval;
	private boolean systemActive;
	
	public DeploymentManager(long timeInterval){
		this.timeInterval = timeInterval;
		systemActive = true;
	}
	
	@Override
	public void run() {
		
		
		DeploymentOperator deploymentOperator = new DeploymentOperator();
		while(systemActive){
			try{
				Thread.sleep(timeInterval);
				
				
				//UNDEPLOYMENT
				
				Server server = Server.getInstance();
				List<String> domainNames = server.getDomainNames();
				
				for(String domainName : domainNames){
					Domain domain = server.getDomain(domainName);
					List<String> publishNameList = domain.getPublishNameList();
					for(String publishName : publishNameList){
						File file = server.getPublishDirectory(domainName, publishName);
						if(!file.exists())
							deploymentOperator.undeploy(domainName, publishName, false);
					}
				}
				

				
				//UNDEPLOYMENT
				
				//AUTO DEPLOYMENT
				
				File deployDirectory = new File(server.getDeployPath());
				File[] newDeployments = deployDirectory.listFiles();
				Deployment deployment = null;
				
				for(File newDeploy : newDeployments){
					try{
						if(newDeploy.isDirectory()){
							deployment = new Deployment(newDeploy);
						} else {
							continue;
						}
						FileUtils.deleteDir(newDeploy);
						deploymentOperator.deploy(deployment);
					} catch (Exception e) {
						e.printStackTrace();
					} 
					
				}
				
				//AUTO DEPLOYMENT
				
			} catch (Exception e) {
			}
		}
		
	}
	
	public void setSystemActive(boolean systemActive) {
		this.systemActive = systemActive;
	}

	public long getTimeInterval() {
		return timeInterval;
	}

	public void setTimeInterval(long timeInterval) {
		this.timeInterval = timeInterval;
	}
	

}
